package com.ptmall.app.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.base.PermissionListener;
import com.ptmall.app.bean.LocalFile;
import com.ptmall.app.bean.LocalImageHelper;
import com.ptmall.app.net.HttpMethods;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.net.okhttp.BusinessResponse;
import com.ptmall.app.net.okhttp.OkHttps;
import com.ptmall.app.ui.adapter.SelectImgAdapter;
import com.ptmall.app.ui.adapter.SpecAdapter;
import com.ptmall.app.utils.AllUtils;
import com.ptmall.app.utils.FileUtils;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.utils.UriUtil;
import com.ptmall.app.view.GetPhotoPop;
import com.ptmall.app.view.NoScrollGridView;
import com.ptmall.app.view.Pic;
import com.ptmall.app.view.TitleBarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/13.
 */

public class ThActivity extends BaseMvpActivity implements BusinessResponse {

    TextView select_yy,th_price;

    PopupWindow popupWindow;
    private View popView;
    EditText th_desc;
    NoScrollGridView img_gv;

    private List<LocalFile> checkedItems = new ArrayList<>();
    private String[] VIDEO_PERMISSION = {
            Manifest.permission.CAMERA,
            //Manifest.permission.RECORD_AUDIO,
            //Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private PopupWindow mPicPopWin;
    private SelectImgAdapter mImgAdapter;
    public static final int TAKE_CAMERA = 0x000001;
    private final int TAKE_PICTURES = 0x000002;
    private GetPhotoPop photo;
    private final int MAX_IMG_COUNT = 3;

    String id;
    RadioButton ysdh,wsdh;

    String tkDesc ="";

    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    Button enter;
    private OkHttps okHttps;

    StringBuffer stringBuffer = new StringBuffer();
    TitleBarView title_bar;

    int postsize;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_th);
    }

    @Override
    public void initViews() {
        ysdh = (RadioButton) findViewById(R.id.ysdh);
        wsdh = (RadioButton) findViewById(R.id.wsdh);
        img_gv = (NoScrollGridView) findViewById(R.id.img_gv);
        select_yy = (TextView) findViewById(R.id.select_yy);
        th_price = (TextView) findViewById(R.id.th_price);
        th_desc = (EditText) findViewById(R.id.th_desc);
        enter = (Button) findViewById(R.id.enter);
        title_bar = (TitleBarView) findViewById(R.id.title_bar);
    }

    @Override
    public void initEvents() {
        okHttps = new OkHttps(this);
        okHttps.addResponseListener(this);
        id = getIntent().getStringExtra("id");
        select_yy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop();
            }
        });
        th_price.setText("￥"+getIntent().getStringExtra("price"));

        mImgAdapter = new SelectImgAdapter(this, position -> {//删除回调
            checkedItems.remove(position);
            mImgAdapter.notifyDataSetChanged();
        }, v -> {//添加回调
            requestRuntimePermisssions(VIDEO_PERMISSION, new PermissionListener() {
                @Override
                public void onGranted() {
                    showPicDialog();
                }

                @Override
                public void onDenied(List<String> deniedList) {
                }
            });
        }, MAX_IMG_COUNT, checkedItems);
        img_gv.setAdapter(mImgAdapter);
        th_desc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                tkDesc = th_desc.getText().toString();
            }
        });
        enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (LocalFile mLocalFile:checkedItems){
                    okHttps.postAsynFile(HttpMethods.BASE_URL+"User/uploadImage",
                            new File(mLocalFile.getOriginalUri()), true, 1);
                    postsize = 0;
                }
            }
        });
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_CAMERA:
                if (resultCode != RESULT_OK) {
                    return;
                }
                if (checkedItems.size() < MAX_IMG_COUNT) {
                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);
                    LocalFile takePhoto = new LocalFile();
                    takePhoto.setBitmap(bm);
                    takePhoto.setOriginalUri(FileUtils.SDPATH + fileName + ".JPEG");
                    takePhoto.setIshttp(false);
                    long size = new File(takePhoto.getOriginalUri()).length();//单位是Byte(1Byte=8bit)
                    takePhoto.setSize(String.valueOf(size));
                    checkedItems.add(takePhoto);
                    mImgAdapter.notifyDataSetChanged();
                }
                break;
            case TAKE_PICTURES:
                checkedItems.addAll(LocalImageHelper.getInstance().getCheckedItems());
                LocalImageHelper.getInstance().getCheckedItems().clear();
                mImgAdapter.notifyDataSetChanged();
                break;
        }
    }
    private void pop() {
        if (null == popupWindow) {
            if (null == popView) {
                popView = LayoutInflater.from(this).inflate(R.layout.popwindow_thyy, null);
                RadioButton yy1 = (RadioButton) popView.findViewById(R.id.yy1);
                RadioButton yy2 = (RadioButton) popView.findViewById(R.id.yy2);
                RadioButton yy3 = (RadioButton) popView.findViewById(R.id.yy3);
                RadioButton yy4 = (RadioButton) popView.findViewById(R.id.yy4);
                Button gb = (Button) popView.findViewById(R.id.gb);

                gb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                    }
                });

                yy1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        popupWindow.dismiss();
                        if(!b){
                            return;
                        }
                        select_yy.setText("多拍/不想要");
                    }
                });
                yy2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        popupWindow.dismiss();
                        if(!b){
                            return;
                        }
                        select_yy.setText("缺货");
                    }
                });
                yy3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        popupWindow.dismiss();
                        if(!b){
                            return;
                        }
                        select_yy.setText("未按时间发货");
                    }
                });
                yy4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        popupWindow.dismiss();
                        if(!b){
                            return;
                        }
                        select_yy.setText("其他");
                    }
                });
            }

            popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setAnimationStyle(R.style.dialogAnim);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
            popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    AllUtils.backgroundAlpha(1.0f, getWindow());
                }
            });
            //popupWindow.showAtLocation(rootView, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            AllUtils.backgroundAlpha(0.5f, getWindow());
            popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 0);
        }
    }

    private void showPicDialog () {
        photo = new GetPhotoPop(ThActivity.this,getWindow());
        photo.setOnClickPhoto(new GetPhotoPop.OnClickPhoto() {
            @Override
            public void OnClickGallery() {
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(openCameraIntent, TAKE_CAMERA);
            }
            @Override
            public void OnClickPhotoGraph() {
                Intent intent = new Intent(ThActivity.this,
                        LocalAlbumActivity.class);
                intent.putExtra("num", MAX_IMG_COUNT - checkedItems.size());
                startActivityForResult(intent, TAKE_PICTURES);
            }
        });
    }

    private void sstk(){

        Map<String,String> map = new HashMap<>();
        if(ysdh.isChecked()){
            map.put("is_shou","1");
        }else {
            map.put("is_shou","2");
        }
        map.put("reason",select_yy.getText().toString());
        map.put("tui_word",tkDesc);
        map.put("orderId",id);
        map.put("images",stringBuffer.deleteCharAt(stringBuffer.length()-1).toString());
        apiDataRepository.ssTk(map, new ApiNetResponse<Object>() {
            @Override
            public void onSuccess(Object data) {
                showMsg("提交成功");
                finish();
            }
        });
    }

    @Override
    public void OnMessageResponse(int id, String jo) {
        switch (id){
            case 1:
                try {
                    JSONObject jsonObject = new JSONObject(jo);
                    stringBuffer.append(jsonObject.getString("image_path")+",");
                    postsize++;
                } catch (Exception e) {
                    e.printStackTrace();
                    showMsg("图片上传失败");
                    postsize = 0;

                    return;
                }
                if(postsize == checkedItems.size()){
                    sstk();
                }
                break;
        }
    }
}
